package org.jeecg.modules.scm.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.boot.starter.rabbitmq.core.BaseRabbiMqHandler;
import org.jeecg.boot.starter.rabbitmq.listenter.MqListener;
import org.jeecg.common.annotation.RabbitComponent;
import org.jeecg.common.base.BaseMap;
import org.jeecg.modules.flow.common.constant.FlowCloudConstant;
import org.jeecg.modules.scm.service.IScmCloudChainService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

/**
 * 流程结束消息接收者
 */
@Slf4j
@RabbitListener(queues = FlowCloudConstant.MQ_FLOW_PROCESS_COMPLETED_EVENT)
@RabbitComponent(value = "processCompletedMsgReceiver")
public class ProcessCompletedMsgReceiver extends BaseRabbiMqHandler<BaseMap> {

    @Autowired
    private IScmCloudChainService scmCloudChainService;

    @RabbitHandler
    public void onMessage(BaseMap baseMap, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        super.onMessage(baseMap, deliveryTag, channel, new MqListener<BaseMap>() {
            @Override
            public void handler(BaseMap map, Channel channel) {
                //业务处理
                log.info("MQ ProcessCompletedMsgReceiver，msg : " + map.entrySet());
                String businessKey = map.get(FlowCloudConstant.FLOW_PROCESS_BUSINESS_KEY);
                // 如果是应收账款流程则需要调用生成云链单接口
                if (StringUtils.isNotBlank(businessKey) && businessKey.split(":").length == 2
                        && businessKey.split(":")[0].equals(FlowCloudConstant.FLOW_PROCESS_TYPE_APPLY_CLOUD_CHAIN)) {
                    scmCloudChainService.onBlockchain(Integer.valueOf(businessKey.split(":")[1]));
                }
            }
        });
    }
}
